package ltd.sumfsy.grain.service.impl;

import ltd.sumfsy.grain.bean.Equipment;
import ltd.sumfsy.grain.bean.RelationUserAndEquip;
import ltd.sumfsy.grain.bean.example.EquipmentExample;
import ltd.sumfsy.grain.bean.example.RelationUserAndEquipExample;
import ltd.sumfsy.grain.mapper.EquipmentMapper;
import ltd.sumfsy.grain.mapper.RelationUserAndEquipMapper;
import ltd.sumfsy.grain.service.EquipmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 设备相关服务实现类
 * @author 范颂扬
 * @create 2021-05-12 22:22
 */
@Service
public class EquipmentServiceImpl implements EquipmentService {

    private final EquipmentMapper equipmentMapper;

    private final RelationUserAndEquipMapper relationMapper;

    @Autowired
    public EquipmentServiceImpl(EquipmentMapper equipmentMapper, RelationUserAndEquipMapper relationMapper) {
        this.equipmentMapper = equipmentMapper;
        this.relationMapper = relationMapper;
    }

    @Override
    public boolean add(Equipment equipment) {
        int res = equipmentMapper.insertSelective(equipment);
        return res > 0;
    }

    @Override
    public boolean deleteById(Integer id) {
        int res = equipmentMapper.updateByPrimaryKeySelective(new Equipment()
                .setId(id).setDelFlag(1));
        return res > 0;
    }

    @Override
    public boolean alterById(Equipment equipment) {
        int res = equipmentMapper.updateByPrimaryKeySelective(equipment);
        return res > 0;
    }

    @Override
    public List<Equipment> queryAll() {
        EquipmentExample example = new EquipmentExample();
        example.createCriteria().andDelFlagEqualTo(0);
        return equipmentMapper.selectByExample(example);
    }

    @Override
    public Equipment queryById(Integer id) {
        return equipmentMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Equipment> queryByTime(Date beginTime, Date endTime) {
        EquipmentExample example = new EquipmentExample();
        example.createCriteria().andProduceTimeBetween(beginTime, endTime)
                .andDelFlagEqualTo(0);
        return equipmentMapper.selectByExample(example);
    }

    @Override
    public List<Equipment> queryByUserId(Integer userId) {
        RelationUserAndEquipExample example = new RelationUserAndEquipExample();
        example.createCriteria().andDelFlagEqualTo(0).andUserIdEqualTo(userId);
        List<RelationUserAndEquip> relations = relationMapper.selectByExample(example);
        List<Integer> equipIds = new ArrayList<>();
        for(RelationUserAndEquip relation : relations) {
            equipIds.add(relation.getEquipId());
        }
        EquipmentExample example1 = new EquipmentExample();
        example1.createCriteria().andDelFlagEqualTo(0).andIdIn(equipIds);
        return equipmentMapper.selectByExample(example1);
    }
}
